import qs from 'qs'
import axios from 'axios'
import {delUrl} from './urlParse'
const refreshToken = 'refresh_token'
const IdToken = 'token'
export const VUE_APP_clientId =  process.env.VUE_APP_TYPE === 'prod' ? 'scm' : 'scm-uat'
export const VUE_APP_userAuthorizationUri = process.env.VUE_APP_TYPE === 'prod' ? 'https://sso.fastfish.com/realms/fastfish/protocol/openid-connect/auth' : 'https://sso-pre.fastfish.com/realms/fastfish/protocol/openid-connect/auth'
export const VUE_APP_logoutUri = process.env.VUE_APP_TYPE === 'prod' ? 'https://sso.fastfish.com/realms/fastfish/protocol/openid-connect/logout' : 'https://sso-pre.fastfish.com/realms/fastfish/protocol/openid-connect/logout'
export function removeAllToken() {
  localStorage.removeItem('userInfo')
  removeIdToken()
  removeRefreshToken()
}

export function getIdToken() {
  return localStorage.getItem(IdToken)
}

export function setIdToken(token) {
  return localStorage.setItem('token', token)
}

export function removeIdToken() {
  return localStorage.removeItem('token')
}
export function getRefreshToken() {
  return localStorage.getItem(refreshToken)
}

export function setRefreshToken(token) {
  localStorage.setItem('refresh_token', token)
}
export function removeRefreshToken() {
  return localStorage.removeItem('refresh_token')
}




/**
 * 通过code获取token
 * @param  {String} code 授权码
 * @return {Promise Object}
 */
export function getToken(code) {
  const redirectUri = encodeURI(delUrl(location.href, ['code', 'state', 'session_state']))
  const params = {
    code,
    redirectUri
  }
  return axios.post(`/webapi/auth/token`, params, {
    headers: {
      Accept: 'application/json',
    }
  })
}


export function decodeJWT(str) {
  // decodeURIComponent(escape(window.atob(("eyJzdWIiOiJ0ZXN0MyIsInVzZXJJZCI6IjEwMTY5MiIsIm5hbWUiOiLmtYvor5V0ZXN0M-a1i-ivlSIsImV4cCI6MTU3OTUxMTY0OH0").replace(/-/g, "+").replace(/_/g, "/"))));
  return JSON.parse(decodeURIComponent(escape(window.atob((str.split('.')[1]).replace(/-/g, "+").replace(/_/g, "/")))))
}
